package com.weituotian.moudle.api.controller;

import com.weituotian.core.controller.BaseController;
import com.weituotian.core.result.Result;
import com.weituotian.core.utils.ApiUtil;
import com.weituotian.system.entity.User;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * app的登录
 * Created by ange on 2017/3/16.
 */
@Controller("apiLoginController")
@RequestMapping("${apiPath}")
public class ApiLoginController extends BaseController {


    @Value("${member.avater}")
    protected String avaterPath;


    /**
     * 登录请求ajax
     *
     * @param username 用户名
     * @param password 密码
     * @return
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public Object doLogin(String username, String password) {
        logger.info("app POST请求登录");

        if (StringUtils.isBlank(username)) {
            return renderError("用户名不能为空");
        }
        if (StringUtils.isBlank(password)) {
            return renderError("密码不能为空");
        }

        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(username, DigestUtils.md5Hex(password).toCharArray());//md5加密密码
        token.setRememberMe(true);

        try {
            subject.login(token);
        } catch (UnknownAccountException e) {
            logger.error("账号不存在：{}", e);
            return renderError("账号不存在");
        } catch (DisabledAccountException e) {
            logger.error("账号未启用：{}", e);
            return renderError("账号未启用");
        } catch (IncorrectCredentialsException e) {
            logger.error("密码错误：{}", e);
            return renderError("密码错误");
        } catch (RuntimeException e) {
            logger.error("未知错误,请联系管理员：{}", e);
            return renderError("未知错误,请联系管理员");
        }

        Result result = new Result();
        result.setSuccess(true);
        result.setMsg("登录成功");
        User user = (User) subject.getPrincipal();

        subject.getSession().setTimeout(2 * 60 * 60 * 1000);//设置2小时,更长时间的超时


        //返回json
        //设置用户
        result.setObj(ApiUtil.getAppUser(user, getAvatarPath()));
        return result;
    }


    /**
     * 手机app再次打开的时候,发送touch,触发shiro的filter自动登录
     *
     * @return
     */
    @RequestMapping(value = "/touch", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public Object touch() {
        Subject subject = SecurityUtils.getSubject();

        Result result = new Result();
        result.setSuccess(true);
        result.setMsg("更新状态成功");
        User user = (User) subject.getPrincipal();

        subject.getSession().setTimeout(2 * 60 * 60 * 1000);//设置2小时,更长时间的超时

        //返回json
        //设置用户
        result.setObj(ApiUtil.getAppUser(user, getAvatarPath()));
        return result;
    }


    /**
     * 退出
     *
     * @return {Result}
     */
    @RequestMapping(value = "/logout", produces = "application/json; charset=utf-8")
    @ResponseBody
    public Object logout() {
//        logger.info("登出");
        Subject subject = SecurityUtils.getSubject();
        subject.logout();

        return renderSuccess("登出成功");
    }
}
